// pages/privacy-settings/privacy-settings.js
const { get, post } = require('../../utils/api.js')
const { showError, showSuccess, showToast } = require('../../utils/util.js')
const { navigateTo, navigateBack } = require('../../utils/router.js')

Page({
  data: {
    // 基础隐私设置
    profileVisibility: 'public', // public, friends, matched, private
    showOnlineStatus: true,
    showLastSeen: true,
    showDistance: true,
    allowDiscovery: true,
    
    // 匹配相关隐私
    hideFromSearch: false,
    autoHideAfterMatch: false,
    requireMutualLike: true,
    limitDailyMatches: false,
    maxDailyMatches: 10,
    
    // 消息隐私
    allowMessagesFrom: 'matched', // all, matched, verified
    readReceiptsEnabled: true,
    typingIndicatorEnabled: true,
    allowVoiceMessages: true,
    blockUnverifiedUsers: false,
    
    // 位置隐私
    shareLocationWithMatches: true,
    showApproximateLocation: true,
    locationAccuracy: 'city', // precise, city, region
    nearbyVisibility: true,
    
    // 数据隐私
    allowDataAnalytics: true,
    shareWithPartners: false,
    personalizedAds: true,
    dataRetentionPeriod: '1year', // 6months, 1year, 2years, forever
    
    // 社交隐私
    communityPostsVisibility: 'public', // public, friends, private
    allowMentions: true,
    moderateComments: false,
    hideLikesCount: false,
    
    // 账号安全
    twoFactorEnabled: false,
    loginNotifications: true,
    suspiciousActivityAlerts: true,
    deviceManagement: true,
    
    // 反欺诈设置
    photoVerificationRequired: false,
    blockSuspiciousAccounts: true,
    reportAutoFilter: true,
    scamDetectionEnabled: true,
    
    // 数据掩码设置
    maskPhoneNumber: true,
    maskEmail: true,
    maskRealName: true,
    showPartialInfo: true,
    
    // 设置选项
    profileVisibilityOptions: [
      { value: 'public', label: '所有人可见', desc: '任何用户都能看到你的资料' },
      { value: 'friends', label: '好友可见', desc: '只有好友能看到你的完整资料' },
      { value: 'matched', label: '匹配用户可见', desc: '只有与你匹配的用户能看到' },
      { value: 'private', label: '仅自己可见', desc: '完全隐私，不会出现在推荐中' }
    ],
    
    messageSourceOptions: [
      { value: 'all', label: '所有人', desc: '任何用户都可以给你发消息' },
      { value: 'matched', label: '匹配用户', desc: '只有与你匹配的用户可以发消息' },
      { value: 'verified', label: '认证用户', desc: '只有通过身份认证的用户可以发消息' }
    ],
    
    locationAccuracyOptions: [
      { value: 'precise', label: '精确位置', desc: '显示准确的地理位置' },
      { value: 'city', label: '城市级别', desc: '只显示所在城市' },
      { value: 'region', label: '地区级别', desc: '只显示所在地区' }
    ],
    
    dataRetentionOptions: [
      { value: '6months', label: '6个月', desc: '6个月后自动删除聊天记录' },
      { value: '1year', label: '1年', desc: '1年后自动删除聊天记录' },
      { value: '2years', label: '2年', desc: '2年后自动删除聊天记录' },
      { value: 'forever', label: '永久保存', desc: '不自动删除聊天记录' }
    ],
    
    // 弹窗控制
    showVisibilityDialog: false,
    showMessageSourceDialog: false,
    showLocationAccuracyDialog: false,
    showDataRetentionDialog: false,
    showResetDialog: false,
    
    // 加载状态
    loading: false,
    saving: false
  },

  onLoad() {
    this.loadPrivacySettings()
  },

  /**
   * 加载隐私设置
   */
  loadPrivacySettings() {
    this.setData({ loading: true })
    
    get('/api/user/privacy-settings')
      .then(data => {
        // 更新所有设置
        this.setData({
          ...data,
          loading: false
        })
      })
      .catch(error => {
        console.error('加载隐私设置失败:', error)
        this.setData({ loading: false })
        showError('加载设置失败，请重试')
      })
  },

  /**
   * 保存隐私设置
   */
  savePrivacySettings() {
    this.setData({ saving: true })
    
    const settings = {
      profileVisibility: this.data.profileVisibility,
      showOnlineStatus: this.data.showOnlineStatus,
      showLastSeen: this.data.showLastSeen,
      showDistance: this.data.showDistance,
      allowDiscovery: this.data.allowDiscovery,
      hideFromSearch: this.data.hideFromSearch,
      autoHideAfterMatch: this.data.autoHideAfterMatch,
      requireMutualLike: this.data.requireMutualLike,
      limitDailyMatches: this.data.limitDailyMatches,
      maxDailyMatches: this.data.maxDailyMatches,
      allowMessagesFrom: this.data.allowMessagesFrom,
      readReceiptsEnabled: this.data.readReceiptsEnabled,
      typingIndicatorEnabled: this.data.typingIndicatorEnabled,
      allowVoiceMessages: this.data.allowVoiceMessages,
      blockUnverifiedUsers: this.data.blockUnverifiedUsers,
      shareLocationWithMatches: this.data.shareLocationWithMatches,
      showApproximateLocation: this.data.showApproximateLocation,
      locationAccuracy: this.data.locationAccuracy,
      nearbyVisibility: this.data.nearbyVisibility,
      allowDataAnalytics: this.data.allowDataAnalytics,
      shareWithPartners: this.data.shareWithPartners,
      personalizedAds: this.data.personalizedAds,
      dataRetentionPeriod: this.data.dataRetentionPeriod,
      communityPostsVisibility: this.data.communityPostsVisibility,
      allowMentions: this.data.allowMentions,
      moderateComments: this.data.moderateComments,
      hideLikesCount: this.data.hideLikesCount,
      twoFactorEnabled: this.data.twoFactorEnabled,
      loginNotifications: this.data.loginNotifications,
      suspiciousActivityAlerts: this.data.suspiciousActivityAlerts,
      photoVerificationRequired: this.data.photoVerificationRequired,
      blockSuspiciousAccounts: this.data.blockSuspiciousAccounts,
      reportAutoFilter: this.data.reportAutoFilter,
      scamDetectionEnabled: this.data.scamDetectionEnabled,
      maskPhoneNumber: this.data.maskPhoneNumber,
      maskEmail: this.data.maskEmail,
      maskRealName: this.data.maskRealName,
      showPartialInfo: this.data.showPartialInfo
    }
    
    post('/api/user/privacy-settings', settings)
      .then(() => {
        this.setData({ saving: false })
        showSuccess('设置已保存')
      })
      .catch(error => {
        console.error('保存隐私设置失败:', error)
        this.setData({ saving: false })
        showError('保存失败，请重试')
      })
  },

  /**
   * 切换开关设置
   */
  onSwitchChange(e) {
    const { field } = e.currentTarget.dataset
    const value = e.detail
    
    this.setData({
      [field]: value
    })
    
    // 自动保存
    this.savePrivacySettings()
  },

  /**
   * 滑块变化
   */
  onSliderChange(e) {
    const { field } = e.currentTarget.dataset
    const value = e.detail.value
    
    this.setData({
      [field]: value
    })
    
    // 延迟保存，避免频繁请求
    clearTimeout(this.saveTimer)
    this.saveTimer = setTimeout(() => {
      this.savePrivacySettings()
    }, 1000)
  },

  /**
   * 显示资料可见性选择
   */
  showProfileVisibilityDialog() {
    this.setData({ showVisibilityDialog: true })
  },

  /**
   * 隐藏资料可见性选择
   */
  hideVisibilityDialog() {
    this.setData({ showVisibilityDialog: false })
  },

  /**
   * 选择资料可见性
   */
  selectProfileVisibility(e) {
    const value = e.currentTarget.dataset.value
    this.setData({
      profileVisibility: value,
      showVisibilityDialog: false
    })
    this.savePrivacySettings()
  },

  /**
   * 显示消息来源选择
   */
  showMessageSourceDialog() {
    this.setData({ showMessageSourceDialog: true })
  },

  /**
   * 隐藏消息来源选择
   */
  hideMessageSourceDialog() {
    this.setData({ showMessageSourceDialog: false })
  },

  /**
   * 选择消息来源
   */
  selectMessageSource(e) {
    const value = e.currentTarget.dataset.value
    this.setData({
      allowMessagesFrom: value,
      showMessageSourceDialog: false
    })
    this.savePrivacySettings()
  },

  /**
   * 显示位置精度选择
   */
  showLocationAccuracyDialog() {
    this.setData({ showLocationAccuracyDialog: true })
  },

  /**
   * 隐藏位置精度选择
   */
  hideLocationAccuracyDialog() {
    this.setData({ showLocationAccuracyDialog: false })
  },

  /**
   * 选择位置精度
   */
  selectLocationAccuracy(e) {
    const value = e.currentTarget.dataset.value
    this.setData({
      locationAccuracy: value,
      showLocationAccuracyDialog: false
    })
    this.savePrivacySettings()
  },

  /**
   * 显示数据保留期限选择
   */
  showDataRetentionDialog() {
    this.setData({ showDataRetentionDialog: true })
  },

  /**
   * 隐藏数据保留期限选择
   */
  hideDataRetentionDialog() {
    this.setData({ showDataRetentionDialog: false })
  },

  /**
   * 选择数据保留期限
   */
  selectDataRetention(e) {
    const value = e.currentTarget.dataset.value
    this.setData({
      dataRetentionPeriod: value,
      showDataRetentionDialog: false
    })
    this.savePrivacySettings()
  },

  /**
   * 管理黑名单
   */
  manageBlocklist() {
    navigateTo('/pages/blocklist/blocklist')
  },

  /**
   * 管理设备
   */
  manageDevices() {
    navigateTo('/pages/device-management/device-management')
  },

  /**
   * 查看数据报告
   */
  viewDataReport() {
    navigateTo('/pages/data-report/data-report')
  },

  /**
   * 设置双因子认证
   */
  setupTwoFactor() {
    if (this.data.twoFactorEnabled) {
      // 禁用双因子认证
      wx.showModal({
        title: '禁用双因子认证',
        content: '确定要禁用双因子认证吗？这会降低账号安全性。',
        confirmText: '禁用',
        confirmColor: '#ff3b30',
        success: (res) => {
          if (res.confirm) {
            this.toggleTwoFactor(false)
          }
        }
      })
    } else {
      // 启用双因子认证
      navigateTo('/pages/two-factor-setup/two-factor-setup')
    }
  },

  /**
   * 切换双因子认证
   */
  toggleTwoFactor(enabled) {
    post('/api/user/two-factor', { enabled })
      .then(() => {
        this.setData({ twoFactorEnabled: enabled })
        showSuccess(enabled ? '双因子认证已启用' : '双因子认证已禁用')
      })
      .catch(error => {
        console.error('设置双因子认证失败:', error)
        showError('设置失败，请重试')
      })
  },

  /**
   * 照片验证设置
   */
  setupPhotoVerification() {
    if (this.data.photoVerificationRequired) {
      wx.showModal({
        title: '关闭照片验证',
        content: '关闭后，你将能够与未进行照片验证的用户匹配。',
        success: (res) => {
          if (res.confirm) {
            this.setData({ photoVerificationRequired: false })
            this.savePrivacySettings()
          }
        }
      })
    } else {
      wx.showModal({
        title: '开启照片验证',
        content: '开启后，你只能与已进行照片验证的用户匹配，提高安全性。',
        success: (res) => {
          if (res.confirm) {
            this.setData({ photoVerificationRequired: true })
            this.savePrivacySettings()
          }
        }
      })
    }
  },

  /**
   * 数据导出
   */
  exportData() {
    wx.showModal({
      title: '导出个人数据',
      content: '我们将准备你的个人数据副本，并通过邮件发送给你。处理时间可能需要1-3个工作日。',
      confirmText: '申请导出',
      success: (res) => {
        if (res.confirm) {
          post('/api/user/export-data')
            .then(() => {
              showSuccess('数据导出申请已提交，我们将通过邮件通知你')
            })
            .catch(error => {
              console.error('申请数据导出失败:', error)
              showError('申请失败，请重试')
            })
        }
      }
    })
  },

  /**
   * 删除账号数据
   */
  deleteAccountData() {
    wx.showModal({
      title: '删除账号数据',
      content: '这将永久删除你的所有数据，包括个人资料、聊天记录、匹配记录等。此操作不可撤销！',
      confirmText: '确认删除',
      confirmColor: '#ff3b30',
      success: (res) => {
        if (res.confirm) {
          // 二次确认
          wx.showModal({
            title: '最终确认',
            content: '请再次确认要删除所有数据。删除后账号将无法恢复！',
            confirmText: '永久删除',
            confirmColor: '#ff3b30',
            success: (res2) => {
              if (res2.confirm) {
                this.performAccountDeletion()
              }
            }
          })
        }
      }
    })
  },

  /**
   * 执行账号删除
   */
  performAccountDeletion() {
    post('/api/user/delete-account')
      .then(() => {
        showSuccess('账号删除申请已提交')
        setTimeout(() => {
          // 跳转到登录页面
          wx.reLaunch({
            url: '/pages/login/login'
          })
        }, 2000)
      })
      .catch(error => {
        console.error('删除账号失败:', error)
        showError('删除失败，请重试')
      })
  },

  /**
   * 重置所有设置
   */
  showResetConfirmation() {
    this.setData({ showResetDialog: true })
  },

  /**
   * 隐藏重置确认
   */
  hideResetDialog() {
    this.setData({ showResetDialog: false })
  },

  /**
   * 确认重置设置
   */
  confirmResetSettings() {
    post('/api/user/reset-privacy-settings')
      .then(() => {
        this.setData({ showResetDialog: false })
        // 重新加载默认设置
        this.loadPrivacySettings()
        showSuccess('设置已重置为默认值')
      })
      .catch(error => {
        console.error('重置设置失败:', error)
        showError('重置失败，请重试')
      })
  },

  /**
   * 查看隐私政策
   */
  viewPrivacyPolicy() {
    navigateTo('/pages/privacy-policy/privacy-policy')
  },

  /**
   * 查看服务条款
   */
  viewTermsOfService() {
    navigateTo('/pages/terms/terms')
  },

  /**
   * 联系客服
   */
  contactSupport() {
    wx.makePhoneCall({
      phoneNumber: '400-123-4567',
      fail: () => {
        wx.setClipboardData({
          data: '400-123-4567',
          success: () => {
            showToast('客服电话已复制到剪贴板')
          }
        })
      }
    })
  }
})